package com.quyeying.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class IdGeneratorSnowflake {
    private long workerId = 0;//机器码
    private long datacenterId = 1;//数据中心id
    private Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);

    @PostConstruct
    public void init() {
        //将机器码创进去--去iPv4
        workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        System.out.println("当前及其的workid：{}");
        workerId = NetUtil.getLocalhostStr().hashCode();
    }

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }
}

